package com.zhenhunfan.io.model.nio.demo02.demo01;

import java.io.IOException;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * <p>Title: Acceptor</p>
 * <p>Description: </p>
 *
 * @author zhenhunfan
 * @version 1.0.0
 * @date 2021/4/1
 */
public class Acceptor2 implements Runnable {

    //多路复用器，主要作用是轮询TCP缓冲区中每个网络IO的数据是否准备好了
    private final Selector selector;
    //可以理解成web服务器
    private final ServerSocketChannel serverSocketChannel;

    public Acceptor2(ServerSocketChannel serverSocketChannel, Selector selector) {
        this.selector = selector;
        this.serverSocketChannel = serverSocketChannel;
    }

    public void run() {
        SocketChannel socketChannel;
        try {
            //拿到客户端连接
            socketChannel = serverSocketChannel.accept();
            if(socketChannel != null){
                //注册感兴趣的读事件
                new AsyncHandler(socketChannel,selector);//这里把客户端通道传给Handler
                //Handler负责接下来的事件处理（除了连接事件以外的事件都可以）
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
